import { useState } from 'react';
import md5 from 'md5';
import { Button, Form, Input } from 'antd-mobile';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons';
// import { useMutation } from '@apollo/client';
import { Link, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { AUTH_TOKEN } from '../../utils/constants';
// import { STUDENT_LOGIN } from '@/graphql/user';
import { showFail, showSuccess } from '../../utils/index.ts';

import style from './index.module.less';

interface IValue {
  password: string;
  username: string;
}

/**
 * 登录页面
 */
const Login = () => {
  const [visible, setVisible] = useState(false);
  const nav = useNavigate();

  // 登录函数
  const login = (obj: any) =>
    // 判断用户账号密码是否正确，正确登录
    axios
      .post('http://localhost:3000/login', {
        username: obj.variables.username,
        password: obj.variables.password,
      })
      .then((res) => ({
        data: {
          studentLogin: {
            code: res.data.code,
            message: res.data.msg,
            token: res.data.AccessToken,
            list: res.data.data,
          },
        },
      }))
      .catch((err) => ({
        data: {
          studentLogin: {
            code: 400,
            message: '登录失败',
            data: err,
          },
        },
      }))
  ;

  // 加载属性
  const [loading] = useState(false);

  const loginHandler = async (values: IValue) => {
    // 调用登录接口
    const res: any = await login({
      // 传入参数
      variables: {
        // 密码加密
        password: md5(values.password),
        username: values.username,
      },
    });

    // 判断是否登录成功
    if (res?.data.studentLogin.code === 200) {
      // 显示成功信息
      showSuccess(res?.data.studentLogin.message);
      // 存储token
      localStorage.setItem(AUTH_TOKEN, 'AUTH_TOKEN');
      // 存储studentID
      localStorage.setItem('Student', JSON.stringify(res?.data.studentLogin.list));
      localStorage.setItem('StudentID', res?.data.studentLogin.list[0].id);
      // 跳转到首页
      nav('/');
      return;
    }
    // 获取返回数据
    const data = res?.data.studentLogin;

    // 显示失败信息
    showFail(data);
  };

  return (
    <div className={style.container}>
      <div className={style.logo}>
        <img
          src="https://water-drop-assets.oss-cn-hangzhou.aliyuncs.com/images/henglogo.png"
          alt=""
        />
      </div>
      <Form
        layout="horizontal"
        onFinish={loginHandler}
        footer={(
          <Button
            loading={loading}
            block
            type="submit"
            color="primary"
            size="large"
          >
            登录
          </Button>
        )}
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: '用户名不能为空',
            },
            {
              pattern: /^(?![0-9]+$)(?![a-z]+$)[a-z0-9]{6,10}$/,
              message: '有且只能包含小写字母和数字，长度大于 6，小于 10',
            },
          ]}
        >
          <Input placeholder="请输入用户名" clearable />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: '密码不能为空',
            },
            {
              pattern: /^(?![0-9]+$)(?![a-z]+$)[a-z0-9]{6,}$/,
              message: '有且只能包含小写字母和数字，长度大于 6',
            },
          ]}
          extra={(
            <div className={style.eye}>
              {!visible ? (
                <EyeInvisibleOutline onClick={() => setVisible(true)} />
              ) : (
                <EyeOutline onClick={() => setVisible(false)} />
              )}
            </div>
          )}
        >
          <Input
            placeholder="请输入密码"
            clearable
            type={visible ? 'text' : 'password'}
          />
        </Form.Item>
      </Form>
      <div>
        没有账号？去
        <Link to="/register">注册</Link>
      </div>
    </div>
  );
};

export default Login;
